<template>
    <div class="main_container">
        <div v-if="pageType=='index'">
            <el-row style="height: 40px;line-height: 40px;margin: 10px 20px 25px 20px;">
                <el-col :span="6">
                    <el-radio-group v-model="filterType" @change="radioChange">
                        <el-radio label="1">按条件筛选</el-radio>
                        <el-radio label="2">按日期范围</el-radio>
                    </el-radio-group>
                </el-col>
                <el-col :span="7" v-if="filterType=='1'">
                    <el-select style="width: 280px;" v-model="order_type" placeholder="请选择"
                        @change="typeChange" clearable>
                        <el-option v-for="item in filterTypes" :key="'filter_'+item.value" 
                            :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </el-col>
                <el-col :span="7" v-else>
                    <el-date-picker type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" 
                        v-model="dateRange" format="yyyy-MM-dd" value-format="yyyy-MM-dd" 
                        :picker-options="handleTime" @change="dateChange"
                        placeholder="请选择日期范围" style="width: 280px;" clearable></el-date-picker>
                </el-col>
                <el-col v-if="tableType=='sub'" :span="7" style="display: flex;align-items: center;">
                    <span style="font-size: 14px;color: #606266;width: auto;">客户名称：</span>
                    <div class="choose_border" @click="showChooseCustomerAlert = true">
                        <span style="color: #c0c4cf;" v-if="!customer_name">请选择</span>
                        <span>{{ customer_name }}</span>
                    </div>
                </el-col>
            </el-row>
            <div class="common_line"></div>
            <el-row style="padding: 5px 14%;">
                <el-col :span="6" class="flex_div">
                    <span class="top_title">期初结余</span>
                    <span class="money" :class="topData.start_money<0?'red':'green'">{{ topData.start_money }}</span>
                </el-col>
                <el-col :span="6" class="flex_div">
                    <span class="top_title">新增欠款</span>
                    <span class="money" :class="topData.add_money<0?'red':'green'">{{ topData.add_money }}</span>
                </el-col>
                <el-col :span="6" class="flex_div">
                    <span class="top_title">已收欠款</span>
                    <span class="money" :class="topData.paid_payment<0?'red':'green'">{{ topData.paid_payment }}</span>
                </el-col>
                <el-col :span="6" class="flex_div">
                    <span class="top_title">期末合计</span>
                    <span class="money" :class="topData.end_money<0?'red':'green'">{{ topData.end_money }}</span>
                </el-col>
            </el-row>
            <div class="common_line"></div>
            
            <div v-if="tableType=='main'" style="display: flex;align-items: center;justify-content: end;padding: 10px 0;">
                <el-checkbox v-model="is_hide_zero">隐藏零欠款</el-checkbox>
            </div>
            <el-table v-if="tableType=='main'" border :data="orders" v-loading="loading" show-summary 
                :summary-method="getSummaries" :max-height="tableHeight" style="margin-top: 15px;">
                <el-table-column align="center" label="客户名称" prop="name" />
                <el-table-column label="期初结余" align="center" prop="start_money_name" />
                <el-table-column label="新增欠款" align="center" prop="add_money_name" />
                <el-table-column label="本期欠款" align="center" prop="gap_money_name" />
                <el-table-column label="已收欠款" align="center" prop="sub_money_name" />
                <el-table-column label="期末合计" align="center" prop="end_money_name" />
                <el-table-column label="操作" width="120" align="center" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                        <el-button
                            size="mini"
                            type="text"
                            @click="navigateToPage(scope.row)"
                            style="font-weight: bold;color: #0099ff;"
                        >对账</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div v-if="tableType=='sub'" style="display: flex;align-items: center;justify-content: space-between;padding: 10px 0;">
                <div style="display: flex;align-items: center;gap: 50px;">
                    <div style="cursor: pointer;display: inline-flex;align-items: center;" @click="backToMainTable">
                        <i class="el-icon-arrow-left" style="color: #aaa;font-size: 18px;"></i>
                        <span style="margin-left: 8px;font-size: 14px;">返回</span>
                    </div>
                    <div style="font-size: 14px;font-weight: 500;">{{ '客户名称：'+customer_name }}</div>
                </div>
                <el-checkbox v-model="is_hide_zero">隐藏零欠款</el-checkbox>
            </div>
            <el-table v-if="tableType=='sub'" border :data="subOrders" v-loading="loading" show-summary 
                :summary-method="getSummaries" :max-height="tableHeight" style="margin-top: 15px;">
                <el-table-column label="单据类型" align="center" prop="order_type" />
                <el-table-column align="center" label="单据编号" prop="corp_order_no" />
                <el-table-column label="日期" align="center" prop="orders_date" />
                <el-table-column label="应收欠款" align="center" prop="orders_fee_name" />
                <el-table-column label="已收欠款" align="center" prop="sub_money_name" />
                <el-table-column label="欠款金额" align="center" prop="pending_payment_name" />
                <el-table-column label="新增欠款" align="center" prop="add_money_name" />
                <el-table-column label="期末合计" align="center" prop="end_money_name" />
                <el-table-column label="操作" width="120" align="center" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                        <el-button
                            size="mini"
                            type="text"
                            @click="toDetail(scope.row)"
                            style="font-weight: bold;color: #0099ff;"
                        >单据详情</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                v-show="total>0"
                background
                style="padding: 32px 16px;background: #fff;text-align: right;"
                @size-change="handleSizeChange"
                @current-change="getNextPageList($event, rememberLists)"
                :current-page.sync="pageParam.page"
                :page-size="pageParam.num"
                layout="total, prev, pager, next, sizes, jumper"
                :page-sizes="[10, 20, 50, 100]"
                :total="total">
            </el-pagination>
        </div>

        <!-- 销售单详情 -->
        <common-dialog :visiable="pageType == 'orderInfo'">
            <order-info :corpId="params.corp_id" :editId="bussinessId" @hidden="hidden"></order-info>
        </common-dialog>

        <!-- 销售退单详情 -->
        <common-dialog :visiable="pageType == 'orderReturnInfo'">
            <order-return-info :corpId="params.corp_id" :editId="bussinessId" @hidden="hidden"></order-return-info>
        </common-dialog>

        <!-- 收款单详情 -->
        <common-dialog :visiable="pageType == 'receiveOrder'">
            <receive-order :corpId="params.corp_id" :editId="bussinessId" @hidden="hidden"></receive-order>
        </common-dialog>

         <!-- 选择客户 -->
        <choose-customer
            :showChooseCustomer="showChooseCustomerAlert"
            :selectUsers="customerList"
            @chooseOK="chooseCustomerOK"
            @hidden="showChooseCustomerAlert=false"
        ></choose-customer>
    </div>
</template>

<script>
import { shouldReceive, customCheckOrder } from '@/api/statistics'
import chooseCustomer from "@/components/chooseCustomer";
import commonDialog from "@/components/commonDialog";

export default {
    name: 'customerCheck',
    components: {
        chooseCustomer,
        commonDialog,
        orderInfo: () => import('./orderInfo.vue'),
        orderReturnInfo: () => import('./orderReturnInfo.vue'),
        receiveOrder: () => import('./receiveOrder.vue'),
    },
    data() {
        return {
            showSalary: false,
            showChooseCustomerAlert: false,
            is_hide_zero: false,
            filterType: '1',  //1 按条件  2 按日期范围
            filterTypes: [
                {id: 1, label: '今日', value: 'cur_day'},
                {id: 2, label: '本周', value: 'cur_weak'},
                {id: 3, label: '本月', value: 'cur_month'},
                {id: 4, label: '本年', value: 'cur_year'}
            ],
            params: {
                corp_id: '',
                start_date: '',
                end_date: '',
                order_type: 'cur_month'
            },
            tableHeight: 420,
            pageType: 'index',
            order_type: 'cur_month',
            dateRange: [],
            handleTime: {
                disabledDate(date) {
                    //disabledDate 文档上：设置禁用状态，参数为当前日期，要求返回 Boolean
                    return date.getTime() > Date.now();
                }
            },
            loading: false,
            pageParam: {
                page: 1,
                num: 10
            },
            total: 0,
            tableType: 'main',
            orders: [],
            copyOrders: [],
            subOrders: [],
            copySubOrders: [],
            rememberLists: [],
            topData: {
                start_money: '0.00',
                end_money: '0.00',
                add_money: '0.00',
                paid_payment: '0.00'
            },
            customer_name: '',
            customerList: [],
            bussinessId: '',  //业务id
        }
    },
    watch: {
        is_hide_zero: function(val) {
            if (this.tableType == 'main'){
                let hideZeroOrders = this.copyOrders.filter(item => parseFloat(item.end_money)!=0)
                this.orders = val ? hideZeroOrders : this.copyOrders
                // 重新计算页数
                this.total = this.orders.length
                this.pageParam.page = 1
                this.getNextPageList('', this.orders)
            }else{
                let hideZeroOrders = this.copySubOrders.filter(item => parseFloat(item.pending_payment)!=0)
                this.subOrders = val ? hideZeroOrders : this.copySubOrders
                // 重新计算页数
                this.total = this.subOrders.length
                this.pageParam.page = 1
                this.getNextPageList('', this.subOrders)
            }
        }
    },
    created() {
        if (window.innerHeight > 1000) {
            this.tableHeight = window.innerHeight - 400
        }
        this.params.corp_id = this.$store.state.corpId
        let nowDate = new Date()
        this.params.start_date = nowDate.getFullYear()+'-'+this.add0(nowDate.getMonth()+1)+'-01'
        this.getData()
    },
    methods: {
        // 补零
        add0(num) {
            if (parseInt(num) < 10){
                num = '0'+ num
            }
            return num
        },
        getSummaries(param) {
            const { columns, data } = param;
            const sums = [];
            let that = this
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = '合计';
                    return;
                }
                if (index===7 && that.tableType=='sub'){
                    sums[index] = '--';
                    return;
                }else if (index===5 && that.tableType=='main'){
                    sums[index] = '--';
                    return;
                }
                const values = data.map(item => Number(item[column.property]));
                if (!values.every(value => isNaN(value))) {
                    sums[index] = values.reduce((prev, curr) => {
                    const value = Number(curr);
                    if (!isNaN(value)) {
                        return prev + curr;
                    } else {
                        return prev;
                    }
                    }, 0);
                    sums[index] = sums[index].toFixed(2);
                } else {
                    sums[index] = '--';
                }
            });

            return sums;
        },
        // 获取数据
        getData() {
            var that = this
            delete that.params['corp']
            delete that.params['customer_id']
            delete that.params['date_order_type']

            that.loading = true
            shouldReceive(this.params).then(res => {
                that.topData.start_money = res.data.data.sum_start_money.toFixed(2)
                that.topData.end_money = res.data.data.sum_end_money.toFixed(2)
                that.topData.add_money = res.data.data.sum_add_money.toFixed(2)
                that.topData.paid_payment = res.data.data.sum_sub_money.toFixed(2)
                let lists = res.data.data.data_list.filter(item => {
                    item.start_money_name = item.start_money.toFixed(2)
                    item.end_money_name = item.end_money.toFixed(2)
                    item.add_money_name = item.add_money.toFixed(2)
                    item.gap_money_name = item.gap_money.toFixed(2)
                    item.sub_money_name = item.sub_money.toFixed(2)
                    return item
                })
                that.copyOrders = lists
                that.total = lists.length
                that.pageParam.page = 1

                if (that.is_hide_zero){
                    lists = lists.filter(item => parseFloat(item.end_money)!=0)
                }
                that.getNextPageList('', lists)
                that.loading = false
            })
        },
        handleSizeChange(val) {
            this.pageParam.num = val
            this.getNextPageList('', this.rememberLists)
        },
        getNextPageList(val, allLists) {
            this.rememberLists = allLists
            let totalPage = 0  //总页数
            if (this.total % this.pageParam.num === 0){  //整除
                totalPage = Math.trunc(this.total / this.pageParam.num)
            }else{
                totalPage = Math.trunc(this.total / this.pageParam.num) + 1
            }

            function chunkArray(arr, size) {
                const result = [];
                for (let i = 0; i < arr.length; i += size) {
                    result.push(arr.slice(i, i + size));
                }
                return result;
            }

            if (this.pageParam.page <= totalPage){
                let groups = chunkArray(allLists, this.pageParam.num)
                if (this.tableType == 'main'){
                    this.orders = groups[this.pageParam.page-1]
                }else{
                    this.subOrders = groups[this.pageParam.page-1]
                }
            }else {
                if (!allLists.length) {
                    if (this.tableType == 'main'){
                        this.orders = []
                    }else{
                        this.subOrders = []
                    }
                }
            }
        },
        navigateToPage(row) {
            this.tableType = 'sub'
            this.customer_name = row.name
            this.params.customer_id = row.id
            this.getSubTableData()
        },
        radioChange(val) {
            if (val == '1'){
                this.typeChange(this.order_type)
            }else{
                this.dateChange(this.dateRange)
            }
        },
        typeChange(val) {
            if (!val) return

            let nowDate = new Date()
            if (val.indexOf("cur_")<0){
                this.params.start_date = nowDate.getFullYear()+'-01-01'
                if(val == 'day'){  //本月，28~31天
                    this.params.start_date = nowDate.getFullYear()+this.add0(nowDate.getMonth()+1)+'-01'
                }
            }else{
                this.params.start_date = ''
            }
            this.params.order_type = val
            if (this.tableType == 'main'){
                this.getData()
            }else{
                this.getSubTableData()
            }
        },
        dateChange(value) {
            if(value && value.length){
                this.params.start_date = value[0]
                this.params.end_date = value[1]
                this.params.order_type = 'customize_date'
                if (this.tableType == 'main'){
                    this.getData()
                }else{
                    this.getSubTableData()
                }
            }
            else{
                this.params.start_date = this.params.end_date = null
                this.params.order_type = ''
                this.tableData = []
            }
        },
        backToMainTable() {
            this.tableType = 'main'
            this.getData()
        },
        getSubTableData() {
            var that = this
            that.params.corp = that.params.corp_id
            that.params.date_order_type = that.params.order_type
            
            that.loading = true
            customCheckOrder(this.params).then(res => {
                that.topData.start_money = res.data.start_money.toFixed(2)
                that.topData.end_money = res.data.end_money.toFixed(2)
                let add_money = 0, paid_money = 0;
                let lists = []
                if (res.data.data_list.length){
                    lists = res.data.data_list.filter(item => {
                        item.actual_receipts = item.actual_receipts || 0
                        if (item.data_type == 'sale'){
                            item.order_type = '销售单'
                        }else if (item.data_type == 'return'){
                            item.order_type = '销售退单'
                        }else if (item.data_type == 'receipt'){
                            item.order_type = '收款单'
                        }
                        add_money = that.$common.plusFloat(add_money, item.add_money)
                        paid_money = that.$common.plusFloat(paid_money, item.actual_receipts)

                        item.end_money_name = item.end_money.toFixed(2)
                        item.add_money_name = item.add_money.toFixed(2)
                        item.sub_money_name = item.actual_receipts.toFixed(2)
                        item.orders_fee_name = item.orders_fee.toFixed(2)
                        item.pending_payment = item.pending_payment?item.pending_payment:0
                        item.pending_payment_name = item.pending_payment.toFixed(2)
                        return item
                    })
                }
                
                that.topData.add_money = add_money.toFixed(2)
                that.topData.paid_payment = paid_money.toFixed(2)

                that.copySubOrders = lists
                that.total = lists.length
                that.pageParam.page = 1
                if (that.is_hide_zero){
                    lists = lists.filter(item => parseFloat(item.pending_payment)!=0)
                }
                that.getNextPageList('', lists)
                that.loading = false
            })
        },
        chooseCustomerOK(res) {
            this.params.customer_id = res.length ? res[0].id : ''
            this.customer_name = res.length ? res[0].name : ''
            this.getSubTableData()
            this.showChooseCustomerAlert = false
        },
        hidden() {
            this.pageType = 'index'
        },
        toDetail(row) {
            this.bussinessId = row.id
            if (row.data_type == 'sale') {
                this.pageType = 'orderInfo'
            }else if (row.data_type == 'return'){
                this.pageType = 'orderReturnInfo'
            }else if (row.data_type == 'receipt'){
                this.pageType = 'receiveOrder'
            }
        }
    }
}
</script>

<style lang="less" scoped>
    @import '../../style/mixin.less';
    .flex_div {
        display: flex;
        flex-direction: column;
        align-items: center;
        .top_title {
            font-size: 14px;
            color: #606266;
            margin-bottom: 14px;
        }
        .money {
            font-size: 22px;
            font-weight: bold;
            // color: red;
            &::before {
                content: '￥';
                font-size: 14px;
            }
        }
        .order {
            &::before {
                content: '';
            } 
        }
        .red {
            color: red;
        }
        .green {
            color: @blue;
        }
    }
</style>
<style>
.el-checkbox {
    color: #333;
}
</style>